﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.IO;

namespace PCRemoteMobileVer
{
    public partial class ViewScreen : PhoneApplicationPage
    {
        private bool isWorking = true;
        private BackgroundWorker getScreenWorker;
        private BackgroundWorker excuteQueryWorker;
        public ViewScreen()
        {
            InitializeComponent();
            //cursor.TransformToVisual(LayoutRoot);
            //cursor.Margin = new Thickness(-700, -400, 0, 0);
        }

        private bool isSending = false;
        void ExcuteQuery(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            while (isWorking)
            {
                if (Queries.Count > 0)
                {
                    string q = Queries.Dequeue();
                    if (string.IsNullOrEmpty(q))
                    {
                        continue;
                    }
                    if (q == "TakeSnap")
                    {
                        isSending = true;
                        MainPage.SendCommand("TakeSnap");
                        byte[] imageData = MainPage.client.ReceiveImage();
                        Dispatcher.BeginInvoke(() =>
                            {
                                if (imageData == null)
                                {
                                    MessageBox.Show("WARNING: Get Screen Error!");
                                    isWorking = false;
                                    //break;
                                }
                                screenViewer.Source = ByteArraytoBitmap(imageData);
                                isSending = false;
                            });
                    }
                    else
                    {
                        MainPage.SendCommand(q);
                    }
                    Thread.Sleep(50);
                }
            }
        }

        void GetScreen(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            while (isWorking)
            {
                if (!isSending)
                {
                    Queries.Enqueue("TakeSnap");
                    Thread.Sleep(200);
                }
            }
            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            isWorking = true;

            getScreenWorker = new BackgroundWorker();
            getScreenWorker.DoWork += GetScreen;
            getScreenWorker.WorkerSupportsCancellation = true;
            getScreenWorker.RunWorkerAsync();
            excuteQueryWorker = new BackgroundWorker();
            excuteQueryWorker.DoWork += ExcuteQuery;
            excuteQueryWorker.WorkerSupportsCancellation = true;
            excuteQueryWorker.RunWorkerAsync();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            isWorking = false;
        }

        public BitmapImage ByteArraytoBitmap(Byte[] byteArray)
        {
            MemoryStream stream = new MemoryStream(byteArray);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(stream);
            return bitmapImage;
        }

        private bool _isfirst = true;
        private Point _begin;
        private Point _end;
        private static int FLUENT = 500;
        private void LayoutRoot_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (_isfirst)
            {
                _begin = e.GetPosition(screenViewer);
                _isfirst = false;
            }
            else
            {
                _end = e.GetPosition(screenViewer);
                _isfirst = true;
                double distanceX = -(_end.X - _begin.X);
                double distanceY = -(_end.Y - _begin.Y);
                //MessageBox.Show("distane (" + distanceX + "," + distanceY + ") margin:(" + cursor.Margin.Left + "," +
                 //               cursor.Margin.Top + ")");
                //cursor.TransformToVisual(screenViewer).Transform(new Point(distanceX, distanceY));

                //cursor.Margin = new Thickness(cursor.Margin.Left - distanceX, cursor.Margin.Top - distanceY, 0,0);
            }
        }

        private int zIndex = 1;
        private void Cursor_OnMouseMove(object sender, MouseEventArgs e)
        {
            Image realSender = (Image)sender;
            Canvas.SetZIndex(realSender, zIndex++ );
            var ttv = cursor.TransformToVisual(screenViewer).Transform(new Point(0, 0));
            System.Diagnostics.Debug.WriteLine(ttv.ToString());
            Queries.Enqueue("MouseMove(" + ttv.ToString() + ")");
        }

        Queue<string> Queries = new Queue<string>();
        private void LayoutRoot_Tap(object sender, GestureEventArgs e)
        {
             Queries.Enqueue("MouseClick");
        }

    }
}